package com.example.demo.service.impl;

import com.example.demo.model.activiti.Task;
import com.example.demo.service.IWorkFlowService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WorkFlowService implements IWorkFlowService {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;

    @Override
    public void startProcessInstance(String processDefinitionKey) {
        ProcessInstance instance = runtimeService
                .startProcessInstanceByKey(processDefinitionKey);

        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info(">>>>>>>>>>> 流程实例ID：" + instance.getId());
        log.info(">>>>>>>>>>> 流程定义ID：" + instance.getProcessDefinitionId());
    }

    /** 测试dynamicAssignmentOperator */
    @Override
    public void dynamicAssignmentOperator(String processDefinitionKey) {
        //启动流程实例的同时，设置流程变量，使用流程变量用来指定任务的办理人，对应bpmn文件中的#{userId}
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("userId", "first_user");

        ProcessInstance instance = runtimeService
                .startProcessInstanceByKey(processDefinitionKey, variables);

        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        log.info(">>>>>>>>>>> 流程实例ID：" + instance.getId());
        log.info(">>>>>>>>>>> 流程定义ID：" + instance.getProcessDefinitionId());

    }

    @Override
    public List<Task> getUserTasks(String assignee) {
        List<org.activiti.engine.task.Task> tasks = taskService.createTaskQuery()
                .taskAssignee(assignee)
                .orderByTaskCreateTime()
                .asc()
                .list();
        List<Task> taskList = new ArrayList<Task>();
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        if (tasks != null && tasks.size() > 0){
            for (org.activiti.engine.task.Task task : tasks) {
                taskList.add(Task.createTaskInformaticFromActiviti(task));
                log.info(">>>>>>>>>>>>>> " + task.toString());
            }
        }
        return taskList;
    }

    @Override
    public void completePersonTask(String taskId) {
        taskService.complete(taskId);
    }

    @Override
    public void completePersonTask(String taskId, Map<String, Object> variables) {
        taskService.complete(taskId, variables);
    }

    @Override
    public void setAssigneeTask(String taskId, String userId) {
        taskService.setAssignee(taskId, userId);
    }
}
